package com.lcq.gulimall.order.web;

import com.lcq.common.exception.WareOutOfStockException;
import com.lcq.gulimall.order.entity.OrderEntity;
import com.lcq.gulimall.order.service.OrderService;
import com.lcq.gulimall.order.vo.OrderConfirmVo;
import com.lcq.gulimall.order.vo.OrderSubmitVo;
import com.lcq.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("order")
public class OrderWebController {
    @Autowired
    OrderService orderService;

    @RequestMapping("/toTrade")
    public String toTrade(Model model){
        OrderConfirmVo orderConfirmVo = orderService.getOrderConfirmInfo();
        model.addAttribute("orderConfirm",orderConfirmVo);
        return "confirm";
    }

    @RequestMapping("/pay.html")
    public String submit(@RequestParam("orderId") Long orderId,Model model){
        OrderEntity order = orderService.getById(orderId);
        model.addAttribute("order",order);
        return "pay";
    }

    @RequestMapping("/submit")
    public String submit(OrderSubmitVo submitVo, RedirectAttributes attributes){
        try {
            SubmitOrderResponseVo responseVo = orderService.submit(submitVo);
            if (responseVo.getCode()==0){
                attributes.addAttribute("orderId",responseVo.getOrderEntity().getId());
                return "redirect:http://order.gulimall.com/order/pay.html";
            }else {
                attributes.addFlashAttribute("errorMsg","订单创建失败，请重试");
                return "redirect:http://order.gulimall.com/order/toTrade";
            }
        }catch (WareOutOfStockException e){
            attributes.addFlashAttribute("errorMsg","库存不足");
            return "redirect:http://order.gulimall.com/order/toTrade";
        }
    }
}
